<template>
  <view class="page-container">
    <!-- 顶部导航 -->
    <S1Header title="权限管理" :on-back="onBack" />

    <!-- 页面说明 -->
    <view class="info-card">
      <view class="info-header">
        <up-icon name="info-circle" size="20" color="#2979ff" />
        <text class="info-title">
          权限组管理
        </text>
      </view>
      <text class="info-desc">
        权限组是角色的权限集合，创建权限组后可在人员管理中为收银员分配相应权限组
      </text>
    </view>

    <!-- 权限组列表 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">
          权限组列表
        </text>
        <view style="width: 200rpx;">
          <up-button type="primary" size="small" style="color: #fff;margin-right: " @click="handleAddGroup">
            <up-icon name="plus" size="16" style="margin-right: 4px;" />
            添加权限组
          </up-button>
        </view>
      </view>

      <view class="group-list">
        <view
          v-for="group in groupList"
          :key="group.id"
          class="group-item"
        >
          <view class="group-info">
            <view class="group-header">
              <text class="group-name">
                {{ group.title }}
              </text>
              <up-tag :text="parseRulesToArray(group.rules).length" type="info" size="mini">
                权限
              </up-tag>
            </view>
            <text class="group-desc">
              {{ getGroupRulesText(group.rules) }}
            </text>
          </view>
          <view class="group-actions">
            <up-button type="primary" size="mini" plain @click="handleEditGroup(group)">
              编辑
            </up-button>
            <up-button type="error" size="mini" plain @click="handleDeleteGroup(group)">
              删除
            </up-button>
          </view>
        </view>

        <!-- 空状态 -->
        <up-empty
          v-if="groupList.length === 0 && !loading"
          mode="data"
          text="暂无权限组"
        >
          <template #bottom>
            <up-button type="primary" size="small" @click="handleAddGroup">
              立即添加
            </up-button>
          </template>
        </up-empty>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-wrapper">
          <up-loading-icon mode="circle" />
          <text class="loading-text">
            加载中...
          </text>
        </view>
      </view>
    </view>

    <!-- 添加/编辑权限组弹窗 -->
    <up-popup
      v-model:show="showDialog"
      mode="center"
      :round="10"
      closeable
      close-icon-pos="top-right"
    >
      <view class="dialog-wrapper">
        <view class="dialog-title">
          {{ isEdit ? '编辑权限组' : '添加权限组' }}
        </view>

        <view class="dialog-form">
          <view class="form-item">
            <view class="form-label">
              <text class="required">
                *
              </text>
              权限组名称
            </view>
            <input
              v-model="formData.title"
              class="form-input"
              placeholder="请输入权限组名称"
            >
          </view>

          <view class="form-item">
            <view class="form-label">
              <text class="required">
                *
              </text>
              权限配置
            </view>
            <view class="rules-container">
              <view
                v-for="rule in availableRules"
                :key="rule.id"
                class="rule-item"
              >
                <up-checkbox
                  :model-value="selectedRules.includes(rule.id.toString())"
                  @change="(checked) => handleRuleChange(rule.id.toString(), checked)"
                  :label="rule.title"
                />
              </view>
            </view>
          </view>
        </view>

        <view class="dialog-footer">
          <up-button style="flex: 1; margin-right: 16rpx;" @click="closeDialog">
            取消
          </up-button>
          <up-button type="primary" style="flex: 1;" @click="handleSubmit">
            确定
          </up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import type { RuleGroup } from '@/api/user/types';
import { onMounted, ref } from 'vue';
import { UserApi } from '@/api';
import S1Header from '@/components/S1Header.vue';

// 从API获取的权限规则列表
const availableRules = ref<{
  id: number;
  name: string;
  title: string;
  icon: string;
  path: string;
  img: string;
}[]>([]);

// 状态管理
const groupList = ref<RuleGroup[]>([]);
const loading = ref(false);
const showDialog = ref(false);
const isEdit = ref(false);

// 表单数据
const formData = ref({
  title: '',
  rules: [] as string[],
});

// 选中的权限
const selectedRules = ref<string[]>([]);

// 编辑时的ID
const editId = ref<number | undefined>(undefined);

// 返回上一页
const onBack = () => {
  uni.navigateBack();
};

// 获取权限描述文本
const getGroupRulesText = (rules: string | undefined) => {
  if (!rules || rules.trim() === '') return '暂无权限配置';

  const ruleIds = rules.split(',').filter(id => id.trim());
  const ruleNames = ruleIds.map((ruleId) => {
    return getRuleName(ruleId.trim());
  });

  return ruleNames.join('、');
};

// 解析权限字符串为数组
const parseRulesToArray = (rules: string | undefined): string[] => {
  if (!rules || rules.trim() === '') return [];
  return rules.split(',').map(id => id.trim()).filter(id => id);
};

// 获取权限规则名称
const getRuleName = (ruleId: string): string => {
  const rule = availableRules.value.find(r => r.id === Number.parseInt(ruleId));
  return rule ? rule.title : `权限${ruleId}`;
};

// 加载权限规则详情
const loadRuleDetails = async () => {
  try {
    const res = await UserApi.getRuleDetail();
    if (res.code === 200 && res.data) {
      availableRules.value = res.data;
    }
    else {
      console.warn('获取权限规则详情失败:', res.msg);
    }
  }
  catch (error) {
    console.error('获取权限规则详情失败:', error);
  }
};

// 加载权限组列表
const loadGroupList = async () => {
  try {
    loading.value = true;

    // 先加载权限规则详情
    await loadRuleDetails();

    const res = await UserApi.getRuleGroup();

    if (res.code === 200 && res.data) {
      groupList.value = res.data;
    }
    else {
      uni.showToast({
        title: res.msg || '获取权限组列表失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('加载权限组列表失败:', error);
    uni.showToast({
      title: '加载失败,请重试',
      icon: 'none',
    });
  }
  finally {
    loading.value = false;
  }
};

// 打开添加权限组弹窗
const handleAddGroup = () => {
  isEdit.value = false;
  editId.value = undefined;
  formData.value = {
    title: '',
    rules: [],
  };
  selectedRules.value = [];
  showDialog.value = true;
};

// 打开编辑权限组弹窗
const handleEditGroup = (group: RuleGroup) => {
  isEdit.value = true;
  editId.value = group.id;
  formData.value = {
    title: group.title,
    rules: parseRulesToArray(group.rules),
  };
  selectedRules.value = parseRulesToArray(group.rules);
  showDialog.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false;
};

// 权限选择变化
const handleRuleChange = (ruleId: string, checked: boolean) => {
  if (checked) {
    // 选中时添加到数组
    if (!formData.value.rules.includes(ruleId)) {
      formData.value.rules.push(ruleId);
    }
  } else {
    // 取消选中时从数组移除
    const index = formData.value.rules.indexOf(ruleId);
    if (index > -1) {
      formData.value.rules.splice(index, 1);
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.title) {
    uni.showToast({
      title: '请输入权限组名称',
      icon: 'none',
    });
    return;
  }

  if (formData.value.rules.length === 0) {
    uni.showToast({
      title: '请至少选择一个权限',
      icon: 'none',
    });
    return;
  }

  try {
    uni.showLoading({
      title: isEdit.value ? '保存中...' : '添加中...',
      mask: true,
    });

    let res;
    if (isEdit.value && editId.value) {
      res = await UserApi.editRuleGroup({
        id: editId.value,
        title: formData.value.title,
        rules: formData.value.rules.join(','),
      });
    }
    else {
      res = await UserApi.addRuleGroup({
        title: formData.value.title,
        rules: formData.value.rules.map(id => id.toString()).join(','),
      });
    }

    uni.hideLoading();

    if (res.code === 200) {
      uni.showToast({
        title: isEdit.value ? '修改成功' : '添加成功',
        icon: 'success',
      });
      closeDialog();
      loadGroupList();
    }
    else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    uni.hideLoading();
    console.error('提交失败:', error);
    uni.showToast({
      title: '操作失败,请重试',
      icon: 'none',
    });
  }
};

// 删除权限组
const handleDeleteGroup = (group: RuleGroup) => {
  uni.showModal({
    title: '提示',
    content: `确定要删除权限组"${group.title}"吗？删除后使用该权限组的收银员将失去对应权限。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true,
          });

          const result = await UserApi.delRuleGroup({
            id: group.id,
          });

          uni.hideLoading();

          if (result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            });
            loadGroupList();
          }
          else {
            uni.showToast({
              title: result.msg || '删除失败',
              icon: 'none',
            });
          }
        }
        catch (error) {
          uni.hideLoading();
          console.error('删除失败:', error);
          uni.showToast({
            title: '删除失败,请重试',
            icon: 'none',
          });
        }
      }
    },
  });
};

// 页面加载
onMounted(() => {
  loadGroupList();
});
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 信息卡片 */
.info-card {
  background: #fff;
  padding: 32rpx;
  margin-bottom: 16rpx;
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.info-title {
  font-size: 30rpx;
  color: #303133;
  font-weight: 500;
  margin-left: 12rpx;
}

.info-desc {
  font-size: 28rpx;
  color: #606266;
  line-height: 1.5;
}

/* 区块 */
.section {
  background: #fff;
  margin-bottom: 16rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 32rpx;
  color: #303133;
  font-weight: 500;
}

/* 权限组列表 */
.group-list {
  padding: 24rpx 32rpx;
}

.group-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 16rpx;
}

.group-item:last-child {
  margin-bottom: 0;
}

.group-info {
  flex: 1;
  min-width: 0;
}

.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.group-name {
  font-size: 30rpx;
  color: #303133;
  font-weight: 500;
  margin-right: 12rpx;
}

.group-desc {
  font-size: 26rpx;
  color: #909399;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.group-actions {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  flex-shrink: 0;
  margin-left: 16rpx;
}

/* 加载状态 */
.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.loading-text {
  margin-top: 16rpx;
  font-size: 28rpx;
  color: #999;
}

/* 弹窗 */
.dialog-wrapper {
  width: 680rpx;
  max-height: 80vh;
  padding: 32rpx;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #303133;
  margin-bottom: 32rpx;
  text-align: center;
}

.dialog-form {

}

.form-item {
  margin-bottom: 24rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
  display: flex;
  align-items: center;
}

.required {
  color: #f56c6c;
  margin-right: 4rpx;
}

.form-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1px solid #dcdfe6;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #2979ff;
}

/* 权限配置 */
.rules-container {
  border: 1px solid #dcdfe6;
  border-radius: 8rpx;
  padding: 20rpx;
  background: #fafafa;
  max-height: 400rpx;
  overflow-y: auto;
}

.rule-item {
  margin-bottom: 16rpx;
}

.rule-item:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  margin-top: 32rpx;
  gap: 16rpx;
}
</style>
